package com.itic.im.redis;

import com.itic.im.core.annotation.ChannelListener;
import com.itic.im.core.exception.ImException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.data.redis.connection.MessageListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * spring容器初始化完成事件
 * Created by yangwl
 */
public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextListener.class);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // root application context
        if (null == contextRefreshedEvent.getApplicationContext().getParent()) {
            Map<String, Object> beans = contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(ChannelListener.class);
            List<String> channels = new ArrayList<>();
            for (Object o : beans.values()) {
                try {
                    MessageListener channelListener = (MessageListener) o;
                    AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(channelListener.getClass(), ChannelListener.class);
                    String channel = (String) attributes.get("value");
                    if(channels.contains(channel)) {
                        throw new ImException(channel + "频道不能重复监听");
                    }
                    channels.add(channel);
                    // 频道上绑定监听
                    RedisImManager.setChannelListeners(channel, channelListener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
